package com.sun.java.object.clone;


import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.StreamCorruptedException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ByteCloneTest
{
	/**
	 * <pre>
	 * 以二进制方式克隆对象
	 * </pre>
	 * @param src 被克隆的对象
	 * @return 克隆的对象
	 */
	public static final Object byteClone(Object src)
	{
		try
		{
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			ObjectOutputStream out = new ObjectOutputStream(baos);
			out.writeObject(src);
			out.close();
			ByteArrayInputStream bin = new ByteArrayInputStream(baos.toByteArray());
			ObjectInputStream in = new ObjectInputStream(bin);
			Object clone = in.readObject();
			in.close();
			return (clone);
		}
		catch (ClassNotFoundException e)
		{
			throw new InternalError(e.toString());
		}
		catch (StreamCorruptedException e)
		{
			throw new InternalError(e.toString());
		}
		catch (IOException e)
		{
			throw new InternalError(e.toString());
		}
	}

	public static void main(String[] args)
	{
		Person p = new Person();
		p.setAge(80);
		p.setName("jerry");
		p.setSex('F');
		List list = new ArrayList();
		list.add("apple");
		list.add("orange");
		list.add("banana");
		Map map = new HashMap();
		map.put("哥哥", "liuliu");
		map.put("姐姐", "linlin");
		map.put("李李", "lili");
		p.setBt(map);
		p.setSth(list);
		Person ps = (Person)ByteCloneTest.byteClone(p);
		ps.setName("benlsoft");
		System.out.println("p----"+p.getName());
		System.out.println("ps---"+ps.getName());
	}
}

